import IconApp from '@/components/icon/IconApp';
import IconBiliBili from '@/components/icon/IconBiliBili';
import IconDouyin from '@/components/icon/IconDouyin';
import IconKuaishou from '@/components/icon/IconKuaishou';
import IconToutiao from '@/components/icon/IconToutiao';
import IconWeb from '@/components/icon/IconWeb';
import IconWeChatChannels from '@/components/icon/IconWeChatChannels';
import IconWeChatOfficialAccount from '@/components/icon/IconWeChatOfficialAccount';
import IconWeibo from '@/components/icon/IconWeibo';
import {
  listExhibitionRecord,
  pageExhibitionRange,
  saveExhibitionRecordSort
} from '@/services/api/api-assess-week-emphasize-exhibition';
import {
  ActionType,
  DragSortTable,
  ProCard,
  ProColumns,
  ProList
} from '@ant-design/pro-components';
import { Flex, message, Radio, Space } from 'antd';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import React, { useState } from 'react';
import DetailRecord from '../record/DetailRecord';
import styles from './TableExhibitionStyle.less';
dayjs.extend(customParseFormat);

interface DragSortExhibitionProps {
  dragSort: boolean | true;
  actionRefProList?: React.Ref<ActionType | undefined>;
  actionRefTable?: React.Ref<ActionType | undefined>;
  type: number;
  rangeId: string | undefined;
  onRefurbish: () => void;
  onExhibitionRefurbish: () => void;
}

const DragSortExhibition: React.FC<DragSortExhibitionProps> = ({
  dragSort,
  actionRefProList,
  actionRefTable,
  type,
  rangeId,
  onRefurbish,
  onExhibitionRefurbish,
}) => {
  // useEffect(() => {
  //   if (!rangeId) {
  //     setSearchParamState({
  //       ...searchParam,
  //       rangeId: rangeId,
  //     });
  //     actionRefProList?.current?.reloadAndRest();
  //     actionRefTable?.current?.reloadAndRest();
  //   }
  // }, [rangeId]);

  const [searchParam, setSearchParamState] = useState({
    dataName: '',
    rangeId: rangeId,
    datahubLevelId: '2000',
    reportType: 1,
    datahubChannelId: '',
  });

  const [recordDataSources, setRecordDataSourceState] = useState<
    AssessWeekEmphasizeExhibitionData.RecordList[]
  >([]);

  const [activeKey, setActiveKey] = useState<string>('1');

  const columns: ProColumns<AssessWeekEmphasizeExhibitionData.RecordList>[] = [
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          排序
        </span>
      ),
      dataIndex: 'sort',
      width: '39px',
      className: 'drag-visible',
      align: 'center',
      hideInTable: !dragSort,
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          标题
        </span>
      ),
      dataIndex: 'name',
      align: 'center',
      ellipsis: true,
      copyable: true,
      width: '40%',
      render: (dom, entity, index, action) => {
        return (
          <div
            style={{
              textAlign: 'left',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
              overflow: 'hidden',
            }}
          >
            <a
              target="_blank"
              style={{
                textAlign: 'start',
              }}
              href={entity.url}
            >
              {entity.name}
            </a>
          </div>
        );
      },
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          来源
        </span>
      ),
      width: '120px',
      dataIndex: 'sourceName',
      align: 'center',
      render: (dom, entity, index, action) => entity.sourceName,
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          账号
        </span>
      ),
      width: '120px',
      dataIndex: 'sourceName',
      align: 'center',

      render: (dom, entity, index, action) => {
        const item = entity.datahubChannelName;

        let icon;
        if (item == '微信公众号') {
          icon = <IconWeChatOfficialAccount width={15} height={15} />;
        } else if (item == '微信视频号') {
          icon = <IconWeChatChannels width={15} height={15} />;
        } else if (item == '微博') {
          icon = <IconWeibo width={15} height={15} />;
        } else if (item == '抖音') {
          icon = <IconDouyin width={15} height={15} />;
        } else if (item == '今日头条') {
          icon = <IconToutiao width={15} height={15} />;
        } else if (item ==  '快手') {
          icon = <IconKuaishou width={15} height={15} />;
        } else if (item == '哔哩哔哩') {
          icon = <IconBiliBili width={15} height={15} />;
        } else if (item == '客户端') {
          icon = <IconApp width={15} height={15} />;
        } else if (item == '网站') {
          icon = <IconWeb width={15} height={15} />;
        }

        return dragSort ? (
          <DetailRecord
            entrance="exhibition"
            id={entity.recordId}
            exhibitionId={entity.id}
            trigger={
              <a>
                <Flex justify={'center'} align={'center'}>
                  {icon}
                  {entity.datahubSourceName}
                </Flex>
              </a>
            }
            onRefurbish={function (): void {}}
            onExhibitionRefurbish={function (): void {
              onExhibitionRefurbish();
              actionRefProList?.current?.reloadAndRest();
              actionRefTable?.current?.reloadAndRest();
            }}
          />
        ) : (
          <a>
            <Flex justify={'center'} align={'center'}>
              {icon}
              {entity.datahubSourceName}
            </Flex>
          </a>
        );
      },
    },
  ];

  const dragSortTableView = (type: number) => {
    let title = '';
    if (type == 3) {
      title = '月-三好作品';
    } else if (type == 4) {
      title = '周-三好作品';
    }
    return (
      <ProCard split="vertical">
        <ProCard colSpan="300px" title={title} ghost>
          <ProList<AssessWeekCollectArticleRangeData.RangePage>
            actionRef={actionRefProList}
            request={async (params, sorter) => {
              const response = await pageExhibitionRange({
                ...params,
                type: type,
              });

              return {
                data: response.data?.data,
                success: true,
                total: response.data?.total,
              };
            }}
            rowKey="id"
            options={false}
            pagination={{
              showQuickJumper: true,
              showSizeChanger: false,
              defaultPageSize: 12,
            }}
            search={false}
            metas={{
              title: {
                dataIndex: 'name',
                render(dom, entity, index, action, schema) {
                  return (
                    <span
                      style={{
                        marginLeft: '18px',
                      }}
                    >
                      {entity.name} / {entity.startDate} - {entity.endDate}
                    </span>
                  );
                },
              },
            }}
            rowClassName={(row: AssessWeekCollectArticleRangeData.RangePage) => {
              return row.id === searchParam.rangeId ? styles['split-row-select-active'] : '';
            }}
            onRow={(record) => {
              return {
                onClick: () => {
                  if (record.id) {
                    setSearchParamState({
                      ...searchParam,
                      rangeId: record.id,
                    });
                    actionRefTable?.current?.reloadAndRest();
                  }
                },
              };
            }}
          />
        </ProCard>
        <ProCard
          ghost
          bodyStyle={{
            paddingLeft: 18,
          }}
        >
          <DragSortTable<AssessWeekEmphasizeExhibitionData.RecordList>
            columns={columns}
            actionRef={actionRefTable}
            rowKey="id"
            request={async (params = {}, sorter) => {
              if (rangeId) {
                const response = await listExhibitionRecord({
                  ...params,
                  ...searchParam,
                });

                setRecordDataSourceState(response.data);

                return {
                  data: response.data,
                  success: true,
                  total: response.data?.length,
                };
              } else {
                return {
                  data: [],
                  success: true,
                  total: 0,
                };
              }
            }}
            dataSource={recordDataSources}
            dateFormatter="id"
            defaultSize={'small'}
            dragSortKey="sort"
            pagination={false}
            search={false}
            onDragSortEnd={async (
              beforeIndex: number,
              afterIndex: number,
              newDataSource: AssessWeekEmphasizeExhibitionData.RecordList[],
            ) => {
              setRecordDataSourceState(newDataSource);

              const response = await saveExhibitionRecordSort({
                ids: newDataSource?.map((item) => item.id),
              });
              if (response.code == 0) {
                message.success('调整成功');
              }
            }}
            options={{
              density: false,
              setting: false,
            }}
            ghost
            toolbar={{
              multipleLine: true,
              tabs: {
                activeKey,
                onChange: (key) => {
                  setActiveKey(key as string);

                  setSearchParamState({
                    ...searchParam,
                    reportType: key,
                  });

                  actionRefTable?.current?.reloadAndRest();
                },
                items: [
                  {
                    key: '1',
                    tab: '好报道',
                  },
                  {
                    key: '2',
                    tab: '好评论',
                  },
                  {
                    key: '3',
                    tab: '好创意报道',
                  },
                ],
              },
              filter: (
                <Space>
                  <Radio.Group
                    defaultValue={'2000'}
                    optionType="button"
                    buttonStyle="solid"
                    size="middle"
                    onChange={(e) => {
                      setSearchParamState({
                        ...searchParam,
                        datahubLevelId: e.target.value,
                      });

                      actionRefTable?.current?.reloadAndRest();
                    }}
                  >
                    <Radio.Button value="2000">市属媒体</Radio.Button>
                    <Radio.Button value="3000">区县媒体</Radio.Button>
                  </Radio.Group>
                  {/* <Select
                    placeholder="全部类型"
                    variant="filled"
                    defaultValue={'0'}
                    style={{ width: '110px' }}
                    options={[
                      { value: '0', label: '全部平台' },
                      { value: '1', label: '官方' },
                      { value: '2', label: '轻骑兵' },
                    ]}
                    onChange={(value) => {
                      if (type == 3) {
                      } else if (type == 4) {
                        setsearchParamState({
                          ...searchParam,
                          reportType: value == '0' ? '' : value,
                        });

                        actionRef.current?.reloadAndRest();
                      }
                    }}
                  />
                  <Select
                    placeholder="全部平台"
                    variant="filled"
                    defaultValue={'0'}
                    style={{ width: '110px' }}
                    options={[
                      { value: '0', label: '全部平台' },
                      { value: '8117112412962885', label: '微信公众号' },
                      { value: '8117112412962886', label: '微信视频号' },
                      { value: '8117112414076995', label: '微博' },
                      { value: '8117112414994505', label: '抖音' },
                      { value: '8117112419123365', label: '今日头条' },
                    ]}
                    onChange={(value) => {
                      if (type == 3) {
                      } else if (type == 4) {
                        setsearchParamState({
                          ...searchParam,
                          datahubChannelId: value == '0' ? '' : value,
                        });

                        actionRef.current?.reloadAndRest();
                      }
                    }}
                  /> */}
                </Space>
              ),
            }}
          />
        </ProCard>
      </ProCard>
    );
  };

  return dragSortTableView(type);
};
export default DragSortExhibition;
